package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {


    @Resource
    private ShopTypeMapper shopTypeMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList() {
        String str="";
        //1.从redis中查询缓存

        //2.查到了缓存，直接返回
        String cache = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY);
        if(StrUtil.isNotBlank(cache)){
            return Result.ok(JSONUtil.toList(cache, Shop.class));
        }
        //3、没有查到缓存，到数据库里查询
        LambdaQueryWrapper<ShopType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ShopType::getSort);
        List<ShopType> shopTypes = shopTypeMapper.selectList(queryWrapper);
        if(shopTypes==null){
            return Result.fail("分类不存在");
        }
        //4.写入缓存并返回
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY,JSONUtil.toJsonStr(shopTypes), 30,TimeUnit.MINUTES);
        return Result.ok(shopTypes);
    }
}
